require "Cocos2d"
require "AudioEngine"
local visibleSize = cc.Director:getInstance():getVisibleSize()
local visibleOrigin = cc.Director:getInstance():getVisibleOrigin()

local GameState = {nomal=1, think=2, showFinal=3, sleep=4}

local game_1_2_1_3_Scene = class("game_1_2_1_3_Scene",function ()
    return cc.Layer:create()
end)
game_1_2_1_3_Scene._perScene=nil
game_1_2_1_3_Scene.__index=game_1_2_1_3_Scene
function game_1_2_1_3_Scene:createScene()
    require "gameScene"
    local layer = game_1_2_1_3_Scene:create()
    layer._perScene = gameSceneInstance
    return layer
end

function game_1_2_1_3_Scene:create()
    local layer = game_1_2_1_3_Scene:new()
    return layer
end

function game_1_2_1_3_Scene:ctor()
    print("ctor")
    local function sceneEventHandler(eventType)
        if eventType == "enter" then
            self:onEnter()
        elseif eventType == "exit" then
            self:onExit()
        end
    end
    self:registerScriptHandler(sceneEventHandler)
    self._role = nil
    self._maxNum = 10 --题目数量
    self._Panel_root = nil
    self.lastWidgetParent = nil
    self.widgetLastNodeSpace = nil
    self._quesTable = {{1,1},{1,2},{1,3},{1,4},{2,1},{2,2},{2,3},{3,1},{3,2},{4,1}}
    self._nowQues = nil -- 当前的题目
    self.isTouchableOrNot = nil
    self.IsSwitchOrNot = nil
    self.score = 0
    self.aaaa=false -- 限制移动猪的过程中重复触摸
    self.bbbb=false
    self.cccc=false
    self.littleGameTimes = nil    -- 小游戏运行了几个
    self._sleepId = nil
    self._actionName = nil
    self.buttonBear = nil
    self._isBingo=true
    self._aniDate={stand={ani={"standby","standby_1","standby_2"},loop=false,music=nil,musicId=nil},
        chuo={ani="chuo",loop=false,music="chuo.MP3",musicId=nil},
        bingo={ani="bingo_1",loop=false,music="bingo1.mp3",musicId=nil},
        right={ani="right",loop=false,music="right1.mp3",musicId=nil},
        wrong={ani="wrong",loop=false,music="wrong1.MP3",musicId=nil},
        think1={ani="think_1",loop=false,music="think1.mp3",musicId=nil},
        think2={ani="think_2",loop=false,music="think2.mp3",musicId=nil},
        sleepstart={ani="sleep_1",loop=false,music="sleeping1.MP3",musicId=nil},
        sleeping={ani="sleep_2",loop=true,music="sleeping.mp3",musicId=nil},
        wakeiup={ani="sleep_3",loop=false,music=nil,musicId=nil}
    }
end

function game_1_2_1_3_Scene:onEnter()
    print("on scene enter")
    self.isTouchableOrNot = false
    self.IsSwitchOrNot = false
    -- 初始化画面
    self._uiLayer = cc.Layer:create()
    self:addChild(self._uiLayer)
    self:runAction(cc.Sequence:create(cc.DelayTime:create(0.1),cc.CallFunc:create(function()
        --        cc.Director:getInstance():getTextureCache():addImage("class2-02-B1.png")
        --        ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("class2-02-E/class2-02-E.ExportJson")
        ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("Ruru/Ruru.ExportJson")
        for i=2, 5 do
            cc.Director:getInstance():getTextureCache():addImage("game_1_2_1_3/all1213_"..i..".png")
        end
        for i=1, 4 do
            cc.Director:getInstance():getTextureCache():addImage("game_1_2_1_3/l1213_"..i..".png")
        end
        for i=1, 4 do
            cc.Director:getInstance():getTextureCache():addImage("game_1_2_1_3/r1213_"..i..".png")
        end
        self:init()
        --        _sprite:removeFromParentAndCleanup()
    end)))


end

function game_1_2_1_3_Scene:onExit()
    cclog("game_1_2_1_3_Scene--->onExit")
    ccs.ArmatureDataManager:getInstance():removeArmatureFileInfo("Ruru/Ruru.ExportJson")
    for i=2, 5 do
        cc.Director:getInstance():getTextureCache():removeTextureForKey("game_1_2_1_3/all1213_"..i..".png")
    end
    for i=1, 4 do
        cc.Director:getInstance():getTextureCache():removeTextureForKey("game_1_2_1_3/l1213_"..i..".png")
    end
    for i=1, 4 do
        cc.Director:getInstance():getTextureCache():removeTextureForKey("game_1_2_1_3/r1213_"..i..".png")
    end
    ccs.SceneReader:destroyInstance()
    ccs.ActionManagerEx:destroyInstance()
    ccs.GUIReader:destroyInstance()
    ccs.ArmatureDataManager:destroyInstance()

end

function game_1_2_1_3_Scene:init()
    cclog("==========>init")
    local m_scene_root = ccs.SceneReader:getInstance():createNodeWithSceneFile("game_1_2_1_3_Scene.json")
    self:addChild(m_scene_root)

    self._Panel_root = m_scene_root:getChildByTag(10003):getChildByTag(2)
    self.littleGameTimes = 1
    self:SceneInit()
    self:runAction(cc.Sequence:create(cc.DelayTime:create(2),cc.CallFunc:create(function()
        self.isTouchableOrNot = true
    end)))
end

--播放动画
function game_1_2_1_3_Scene:playAction(_type)
    if _type==self._aniDate.stand then
        local function callBack()
            cclog("sleep===>")
            self._state=GameState.sleep
            self:playAction(self._aniDate.sleepstart)
        end
        if self._sleepId==nil then
            self._sleepId=self:runAction(cc.Sequence:create(cc.DelayTime:create(25),cc.CallFunc:create(callBack)))
            --        else
            --            self:stopAction(self._sleepId)
            --            self._sleepId=nil
            --            self._sleepId=self:runAction(cc.Sequence:create(cc.DelayTime:create(15),cc.CallFunc:create(callBack)))
        end
    else
        if self._sleepId~=nil then
            self:stopAction(self._sleepId)
            self._sleepId=nil
        end
    end

    local aniNames=_type.ani
    local loop=_type.loop
    local musicName=_type.music
    --    if musicName~=nil then
    --        cclog("musicName-->"..musicName)
    --    end
    if type(aniNames)=="table" then
        math.randomseed(tostring(os.time()):reverse():sub(1, 6))
        aniNames=aniNames[math.random(1,3)]
        --        if aniNames=="standby_1" then musicName= "look2.mp3" end
        --        if aniNames=="standby_2" then musicName="smell.mp3" end
    end
    if self._actionName==_type and _type~=self._aniDate.stand then print("return") return end
    for k,v in pairs(self._aniDate) do
        if v.musicId~=nil then
            AudioEngine.stopEffect(v.musicId)
            v.musicId=nil
        end
    end
    self._actionName=_type
    --    cclog("aniNames----->"..aniNames)
    self._role:getAnimation():play(aniNames)
    if musicName~=nil then
        _type.musicId=AudioEngine.playEffect(musicName,_type.loop)
    end
end

-- 初始化画面
function game_1_2_1_3_Scene:SceneInit()
    self:runAction(cc.Sequence:create(cc.DelayTime:create(1.0),cc.CallFunc:create(function() 
        AudioEngine.playMusic("game3.mp3",true)
    end)))
    -- 动画
    ccs.ArmatureDataManager:getInstance():removeArmatureFileInfo("ani/Ruru/Ruru.ExportJson")
    ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("ani/Ruru/Ruru.ExportJson")
    self._role=ccs.Armature:create("Ruru")
    self._Panel_root:addChild(self._role,2)
    self._role:setPosition(cc.p(350,270))
    -- 动画
    local function animationEvent(armatureBack,movementType,movementID)
        local id = movementID
        if movementType == ccs.MovementEventType.loopComplete or movementType==ccs.MovementEventType.complete then
            if id == "standby"  or id=="standby_1" or id=="standby_2" then
                --            print("jinru")
                self:playAction(self._aniDate.stand)
            end
            if id=="chuo" then
                self:playAction(self._aniDate.stand)
                self._state=GameState.nomal
            end
            if id=="think_1" or "think_2" then
                self:playAction(self._aniDate.stand)
            end
            if id=="wrong" then
                --            cclog("adadas")
                --                self:FinalcallBack()
                self:playAction(self._aniDate.stand)
                self._state=GameState.nomal

            end
            if id=="right" or id=="bingo_1"then
                cclog("----------createNumber>")
                self:playAction(self._aniDate.stand)
                self._state=GameState.nomal
            end
            if id=="sleep_1" then
                --                self._state=GameState.sleep
                self:playAction(self._aniDate.sleeping)
            end
            if id =="sleep_2" then
                --                self._state=GameState.sleep
                self:playAction(self._aniDate.sleeping)
            end
            if id=="sleep_3" then
                --                AudioEngine.stopEffect(self.musicId)
                --                self._state=GameState.sleep
                if self._nextAction~=nil then
                    cclog("adada")
                    self:playAction(self._nextAction)
                    self._nextAction=nil
                else
                    cclog("adadadadad")
                    self:playAction(self._aniDate.stand)
                end
            end
        end
    end
    self._role:getAnimation():setMovementEventCallFunc(animationEvent)
    self:playAction(self._aniDate.stand)
    self.buttonRabbit = self._Panel_root:getChildByName("Button_rabbit")
    self.buttonRabbit:setOpacity(0)
    self.buttonRabbit:addTouchEventListener( function ( pSender, eventType )
        if eventType ~= ccui.TouchEventType.ended then return  end
        if eventType == ccui.TouchEventType.ended then
            cclog("----buttonBear_touchdown")
            if self._actionName==self._aniDate.stand then --站立被点击
                print("站立被点击")

                self:playAction(self._aniDate.chuo)
            end
            if self._state==GameState.sleep then --睡觉被点击
                self:playAction(self._aniDate.wakeiup)
                --AudioEngine.stopEffect(self.musicId)
                self._state=GameState.nomal
            end
        end
    end)
    self:runAction(cc.Sequence:create(cc.DelayTime:create(1.0),cc.CallFunc:create(function() 
        self:InitGame()
    end)))

end

function game_1_2_1_3_Scene:InitQues()
    if self.littleGameTimes <=self._maxNum then --
        local t_index = math.random(1,#self._quesTable)
        self._nowQues = self._quesTable[t_index]
        table.remove(self._quesTable,t_index)
        local quesSum = self._nowQues[1]+self._nowQues[2]
        self._Panel_root:getChildByName("Panel_ques"):getChildByName("Image_20"):setOpacity(0)
        local quesImg = self._Panel_root:getChildByName("Panel_ques"):getChildByName("Image_2")
        quesImg:loadTexture("l1213_"..self._nowQues[1]..".png")
        local popImage = self._Panel_root:getChildByName("Image_15")
        popImage:loadTexture("all1213_"..quesSum..".png")

    end
end

function game_1_2_1_3_Scene:InitChoice()
    -----------触摸事件
    -- 触摸开始
    local function touch(pSender, touchEventType)
        if touchEventType == ccui.TouchEventType.began  then
            print("---------------------------TOUCH_EVENT_BEGAN")
            if self._sleepId~=nil then
                self:stopAction(self._sleepId)
                self._sleepId=nil
            end
            local function nosleepFunc()
                if self._state==GameState.sleep then
                    self._nextAction=self._aniDate.stand
                    self:playAction(self._aniDate.wakeiup)
                    self._state = GameState.nomal
                    --AudioEngine.stopEffect(self.musicId)
                end
            end
            self:runAction(cc.Sequence:create(cc.DelayTime:create(0.0),cc.CallFunc:create(nosleepFunc)))
            if self.aaaa == true then return end
            if self.isTouchableOrNot == false then cclog("ffaa") self.notMove =true return end
            if self.IsSwitchOrNot == true then cclog("正在切换。") return end
            local worldSpace = pSender:convertToWorldSpace(cc.p(pSender:getContentSize().width/2,
                pSender:getContentSize().height/2))
            --print("/././",worldSpace.x,worldSpace.y)
            self.widgetLastWorldSpace = worldSpace
            --print("ddddd/././",this.widgetLastWorldSpace.x,this.widgetLastWorldSpace.y)

            -- 存放当前控件的相对位置
            local _x,_y = pSender:getPosition()
            print(".he.......",_x,_y)
            self.widgetLastNodeSpace = cc.p(pSender:getPositionX(),pSender:getPositionY())

            -- 存储当前触摸控件的父节点
            self.lastWidgetParent = pSender:getParent()
            self.movePoint = pSender:getTouchBeganPosition()
            cclog("self.movePoint(began):"..self.movePoint.x)
            self.notMove =false
        elseif touchEventType == ccui.TouchEventType.moved then
            print("---------------------------TOUCH_EVENT_MOVED")
            if self.bbbb == true then return end
            if self.isTouchableOrNot == false then self.notEd = true return end
            if self.notMove ==true then cclog("hhhbbb") return end
            if self.IsSwitchOrNot == true then cclog("正在切换。") return end
            cclog("self.movePoint(move):"..self.movePoint.x)
            self.lastPoint = self.movePoint
            self.movePoint = pSender:getTouchMovePosition()
            --            cclog("vvl;"..self.lastPoint)
            --            cclog("lll;"..self.movePoint)

            local offset = cc.pSub(self.movePoint, self.lastPoint)
            local x__,y__ = pSender:getPosition()
            local toPoint = cc.pAdd(cc.p(x__,y__),offset)
            pSender:setPosition(toPoint)
            self.notEd =false
            -- 触摸结束事件，在这里决定应该把物品放置在那一个背包或者物品格内。
        else
            print("---------------------------TOUCH_EVENT_ENDED")
            if self.cccc == true then return end
            if self.isTouchableOrNot == false then return end
            if self.notEd ==true then return end
            if self.IsSwitchOrNot == true then cclog("正在切换。") return end
            local desti = self._Panel_root:getChildByName("Panel_ques"):getChildByName("Image_2")
            self.aaaa=true
            self.bbbb=true
            self.cccc=true
            local DesPos = desti:convertToWorldSpaceAR(cc.p(0,0))
            cclog("desposX:"..DesPos.x..",desposY:"..DesPos.y)
            --            local DesPos = cc.p(desti:getPositionX(), desti:getPositionY())
            --                local usedSlot_wigt = self._box_card
            local _x_,_y_ = pSender:getPosition()
            local worldSpace = pSender:convertToWorldSpaceAR(cc.p(0,0))
            local rectDes = cc.rect(DesPos.x-162,DesPos.y-140,316,289)
            local rectpSender = cc.rect(worldSpace.x,worldSpace.y-145,316,290)--cc.rect(_x_-69,_y_-90,139,181)

            --                if cc.rectIntersectsRect(rectDes, rectpSender) then
            if cc.pGetDistance(DesPos,worldSpace)<=100 then -- todo
                cclog("接触了")
                self.aaaa=false
                self.bbbb=false
                self.cccc=false
                if tonumber(pSender:getName()) ==self._nowQues[2] then
                    self.IsSwitchOrNot = true
                    AudioEngine.playEffect("jinru.mp3")
                    local r_img = self._Panel_root:getChildByName("Panel_ques"):getChildByName("Image_20")
                    r_img:loadTexture("r1213_"..self._nowQues[2]..".png")
                    r_img:setOpacity(255)
                    --                    local worspace = r_img:convertToWorldSpace(cc.p(0,0))
                    local p =cc.ParticleSystemQuad:create("particle/game_1_2_1_3/game_1_2_1_3_jinru.plist")
                    --                    p:setSpeed(100)
                    --                    p:setStartSize(30)
                    --                    p:setEndSize(30)
                    --                    p:setStartColor(cc.c4f(0.9,1,1,1))
                    --                    p:setStartColorVar(cc.c4f(0,0,0,0))
                    --                    p:setEndColor(cc.c4f(0.9,1,1,1))
                    --                    p:setEndColorVar(cc.c4f(0,0,0,0))
                    --                    p:setBlendAdditive(false)
                    p:setPosition(cc.p(691,384))
                    self._Panel_root:addChild(p,333)
                    pSender:setOpacity(0)
                    pSender:setPosition(self.widgetLastNodeSpace)
                    if self._isBingo==true then
                        if self._state==GameState.sleep then
                            self._nextAction=self._aniDate.bingo
                            self:playAction(self._aniDate.wakeiup)
                            AudioEngine.stopEffect(self.musicId)
                        else
                            self:playAction(self._aniDate.bingo)
                        end
                        self.score = self.score + 10
                        --                    self.score = self.score + 10
                    else
                        if self._state==GameState.sleep then
                            self._nextAction=self._aniDate.right
                            self:playAction(self._aniDate.wakeiup)
                            AudioEngine.stopEffect(self.musicId)
                        else
                            self:playAction(self._aniDate.right)
                        end
                        self.score = self.score + 5
                    end
                    
                    self._perScene:movePer(self.score,cc.p(0,0))
                    self:runAction(cc.Sequence:create(cc.DelayTime:create(2.0),cc.CallFunc:create(function()
                        ccs.ActionManagerEx:getInstance():playActionByName("game_1_2_1_3_Ui.json","Come_Out",cc.CallFunc:create(function()
                            ccs.ActionManagerEx:getInstance():playActionByName("game_1_2_1_3_Ui.json","popMiss")
                            ccs.ActionManagerEx:getInstance():playActionByName("game_1_2_1_3_Ui.json","Choice_down",cc.CallFunc:create(function()
                                cclog("self.littleGameTimes:"..self.littleGameTimes)
                                if self.littleGameTimes == self._maxNum+1 then
                                    self:runAction(cc.Sequence:create(cc.DelayTime:create(0.3),cc.CallFunc:create(function()
                                        self.isTouchableOrNot =false
                                        self._role:getAnimation():gotoAndPause(1)
                                        if self._sleepId~= nil then
                                            self:stopAction(self._sleepId)
                                            self._sleepId=nil
                                        end
                                        self._perScene:endLayer(1,2,1,3,self.score)
                                        return
                                    end)))
                                    return

                                end                                
                                -- 为下一题初始化
                                self:InitGame()
                            end))
                        end))
                    end)))
                else
                    self._isBingo=false
                    if self._state==GameState.sleep then
                        self:playAction(self._aniDate.wakeiup)
                        --                    AudioEngine.stopEffect(self.musicId)
                        self._nextAction=self._aniDate.wrong
                    else
                        self:playAction(self._aniDate.wrong)
                    end
                    AudioEngine.playEffect("rebound.mp3",false)
                    --                        pSender:retain()
                    --                        pSender:removeFromParent(true)
                    --                        self.lastWidgetParent:addChild(pSender,100)
                    --                        pSender:release()
                    cclog("----xx>"..self.widgetLastNodeSpace.x)
                    local moveTo = cc.MoveTo:create(1.0, self.widgetLastNodeSpace)
                    local ease = cc.EaseExponentialOut:create(moveTo)
                    pSender:runAction(ease)
                end

            else
                print("未接触")
                AudioEngine.playEffect("rebound.mp3",false)
                cclog("----xx>"..self.widgetLastNodeSpace.x)
                local moveTo = cc.MoveTo:create(1.0,self.widgetLastNodeSpace)
                local ease = cc.EaseExponentialOut:create(moveTo)
                pSender:runAction(cc.Sequence:create(ease,cc.CallFunc:create(function()
                    self.aaaa=false
                    self.bbbb=false
                    self.cccc=false
                    self.notMove = true
                    self.notEd = true
                end)))
            end
        end
    end

    if self.littleGameTimes <=self._maxNum then --
        math.randomseed(tostring(os.time()):reverse():sub(1, 6))
        --    self.nowNum = num
        local rightNum = self._nowQues[2]
        --        local tx1 = ccui.imageView:create("r1213_"..rightNum..".png")
        local num_table = {1,2,3,4}
        table.remove(num_table,rightNum)
        local num_index = math.random(1,#num_table)
        local num2 = num_table[num_index]
        table.remove(num_table,num_index)
        num_index = math.random(1,#num_table)
        local num3 = num_table[num_index]
        local temNum = {rightNum,num2,num3}
        for idx=1, 3 do
            local image = self._Panel_root:getChildByName("Panel_Choice"):getChildByTag(24+idx)
            --            cclog("-----------k>"..idx)
            image:setOpacity(255)
            local t= math.random(1,#temNum) --
            image:loadTexture("r1213_"..temNum[t]..".png")
            image:setName(""..temNum[t])
            image:addTouchEventListener(touch)
            image:setTouchEnabled(true)
            table.remove(temNum,t)
        end

    end
end

function game_1_2_1_3_Scene:ComeIn()
    ccs.ActionManagerEx:getInstance():playActionByName("game_1_2_1_3_Ui.json","Come_In",cc.CallFunc:create(function()
        self:playAction(self._aniDate.think1)
        ccs.ActionManagerEx:getInstance():playActionByName("game_1_2_1_3_Ui.json","Choice_Up",cc.CallFunc:create(function()
            ccs.ActionManagerEx:getInstance():playActionByName("game_1_2_1_3_Ui.json","popAc",cc.CallFunc:create(function()
                self.IsSwitchOrNot = false
                self.isTouchableOrNot = true
            end))
        end))
    end))

end

function game_1_2_1_3_Scene:goOut()
    ccs.ActionManagerEx:getInstance():playActionByName("game_1_2_1_3_Ui.json","Come_Out")
end

function game_1_2_1_3_Scene:InitGame()
    self.isTouchableOrNot = false
    self.IsSwitchOrNot = true
    self._isBingo=true
    self.notMove = true
    self.notEd = true
    self:InitQues()
    self:InitChoice()
    self:ComeIn()

    -- 变更数据
    self.littleGameTimes = self.littleGameTimes +1
end

function crt_game_1_2_1_3_Scene()
    local _scene = game_1_2_1_3_Scene:createScene()
    return _scene
end